package com.xuan.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.xuan.constants.CommonConstants.*;

@Configuration
public class RabbitMQConfig {

    public RabbitMQConfig() {
        System.out.println("RabbitMQConfig init...");
    }
    /**
     * 消息转换器
     * 转换成json格式
     * @return
     */
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 声明RabbitMQ客户端
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(messageConverter());
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息成功到达Broker");
            } else {
                System.out.println("消息发送失败: " + cause);
            }
        });
        return template;
    }
    //
    /**
     * 声明日志记录消息队列
     * @return
     */
    @Bean
    public Queue queue() {
        return new Queue(LOGGING_QUEUE, true);
    }

    /**
     * 直连交换机
     * @return
     */
    @Bean
    public DirectExchange directExchange() {
        // 持久化，非自动删除
        return new DirectExchange(LOGGING_EXCHANGE, true, false);
    }

    /**
     * 绑定队列和交换机
     * @return
     */
    @Bean
    public Binding binding() {
        return BindingBuilder
                .bind(queue())
                .to(directExchange())
                .with(LOGGING_ROUTING_KEY);
    }

}
